﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using BigScreen.Conmmon;
using BigScreen.Models;



using LiveChartsCore.SkiaSharpView;
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView.Painting;
using SkiaSharp;
using System.Windows.Markup;
using LiveChartsCore.SkiaSharpView.VisualElements;
using LiveChartsCore.Measure;
using LiveChartsCore.SkiaSharpView.Painting.Effects;
using LiveChartsCore.Drawing;
using System.Threading;
using System.Collections.Immutable;
using System.Windows;

namespace BigScreen.ViewModels
{
    public class MainWindowViewModel : PropertyChangedBase
    {
        //汇总
        private ObservableCollection<TaskBar> taskBars;

        public ObservableCollection<TaskBar> TaskBars
        {
            get { return taskBars; }
            set { taskBars = value; SetPropertyChanged(); }
        }

        /// <summary>
        /// 房源概况
        /// </summary>
        public ISeries[] CityProfileSeries { get; set; }
        public Axis[] CityProfileXAxes { get; set; }

        /// <summary>
        /// 结构占比
        /// </summary>
        public IEnumerable<ISeries> StructureRatioSeries { get; set; }
        public IEnumerable<ISeries> AreaStructureRatioSeries { get; set; }
        public LabelVisual StructureRatioTitle { get; set; } = new LabelVisual
        {
            Text = "户型结构占比",
            TextSize = 16,
            Padding = new LiveChartsCore.Drawing.Padding(10),
            Paint = new SolidColorPaint
            {
                Color = SKColors.White,
                SKTypeface = SKFontManager.Default.MatchCharacter('汉') // 汉语 
            },
        };

        public LabelVisual AreaStructureRatiosTitle { get; set; } = new LabelVisual
        {
            Text = "面积结构占比",
            TextSize = 16,
            Padding = new LiveChartsCore.Drawing.Padding(10),
            Paint = new SolidColorPaint
            {
                Color = SKColors.White,
                SKTypeface = SKFontManager.Default.MatchCharacter('汉') // 汉语 
            },
        };

        //Legend设置
        public SolidColorPaint LegendTextPaint { get; set; } =
           new SolidColorPaint
           {
               Color = SKColors.White,
               Style = SKPaintStyle.StrokeAndFill,
               SKTypeface = SKFontManager.Default.MatchCharacter('汉') // 汉语 
           };

        //Tooltip设置
        public SolidColorPaint TooltipTextPaint { get; set; } =
           new SolidColorPaint
           {
               Color = SKColors.Black,
               Style = SKPaintStyle.StrokeAndFill,
               SKTypeface = SKFontManager.Default.MatchCharacter('汉') // 汉语 
           };

        //YAxes设置
        public Axis[] YAxes { get; set; } = new Axis[]{new Axis
        {
            LabelsPaint = new SolidColorPaint
            {
                Color = SKColors.White
            }
        } };

        //销售排行榜
        private ObservableCollection<SaleBillboard> saleBillboards;
        public ObservableCollection<SaleBillboard> SaleBillboards
        {
            get { return saleBillboards; }
            set { saleBillboards = value; }
        }

        //签约和回款
        public IEnumerable<ISeries> SignedSeries { get; set; }
        public IEnumerable<ISeries> PaymentCollectionSeries { get; set; }

        //人群分析
        public PolarAxis[] AgeAngleAxes { get; set; }
        public IEnumerable<ISeries> AgeSeries { get; set; }
        //半径说明
        public PolarAxis[] RadiusAxes { get; set; }
        public PolarAxis[] IncomeAngleAxes { get; set; }
        public IEnumerable<ISeries> IncomeSeries { get; set; }
        //销售趋势
        public IEnumerable<ISeries> SaleTrendSeries { get; set; }
        public Axis[] SaleTrendXAxes { get; set; }

        Random random = new Random();

        /// <summary>
        /// 构造函数
        /// </summary>
        public MainWindowViewModel()
        {
            Init();
            DynamicData();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void Init()
        {

            #region 汇总数据
            taskBars = new ObservableCollection<TaskBar>();
            taskBars.Add(new TaskBar() { Icon = "&#xe610;", Title = "备案总套数", Value = 652413, BackgroundColor = "#8a91c7", Unit = "套" });
            taskBars.Add(new TaskBar() { Icon = "&#xe603;", Title = "已售总套数", Value = 365421, BackgroundColor = "#ffd0c0", Unit = "套" });
            taskBars.Add(new TaskBar() { Icon = "&#xe622;", Title = "总营收", Value = 961451, BackgroundColor = "#b0e4e6", Unit = "万元" });
            #endregion

            #region 房源柱状图数据
            var city = new[] { "北京", "上海", "深圳", "广州", "南京", "杭州", "南宁", "沈阳", "天津", "重庆", "成都", "哈尔滨", "澳门", "台北" };

            List<CityProfile> cityProfiles = new();
            for (int i = 0; i < city.Length; i++)
            {
                cityProfiles.Add(new CityProfile { Name = city[i], Filing = random.Next(1, 20), Sold = random.Next(1, 15) });
            }


            CityProfileSeries = new ISeries[] {
            new ColumnSeries<CityProfile>
            {
               // Fill = null,
               // GeometrySize = 10,//点大小
                Name = "备案套数",
                // use the line smoothness property to control the curve
                // it goes from 0 to 1
                // where 0 is a straight line and 1 the most curved
               // LineSmoothness = 0,//平滑度
             //MaxBarWidth = 10,//柱形宽度
            // GroupPadding = 10,//柱子间隔
            //IgnoresBarPosition = true,一组柱子是否合并
                TooltipLabelFormatter = point => $"{point.Model.Name} {point.PrimaryValue}套",//提示框显示内容格式化
                Values = cityProfiles,
                Mapping=(city,point)=>{
                    point.PrimaryValue=city.Filing;
                    point.SecondaryValue=point.Context.Index;
                },
            },
            new ColumnSeries<CityProfile>
            {
                Name = "已售套数",
               DataLabelsRotation=45,
                 TooltipLabelFormatter = point => $"{point.Model.Name} {point.PrimaryValue}套",
                  Values = cityProfiles,
                Mapping=(city,point)=>{
                    point.PrimaryValue=city.Sold;
                    point.SecondaryValue=point.Context.Index;
                },
            }
            };

            CityProfileXAxes = new Axis[]{
                new Axis
                {
                    Labels = city,
                    LabelsRotation = 0,
                  //  SeparatorsPaint = new SolidColorPaint(new SKColor(200, 200, 200)),
                    SeparatorsAtCenter = false,
                   // TicksPaint = new SolidColorPaint(new SKColor(35, 35, 35)),
                    TicksAtCenter = true,
                    LabelsPaint = new SolidColorPaint{
                        SKTypeface = SKFontManager.Default.MatchCharacter('汉'),
                         Color = SKColors.White},

                }
            };
            #endregion

            #region 结构占比数据
            List<StructureRatio> HouseStructureRatios = new List<StructureRatio>();
            List<StructureRatio> AreaStructureRatios = new List<StructureRatio>();
            var House = new[] { "一居室", "两居室", "三居室", "四居室", "其他" };
            var Area = new[] { "60m²以下", "60m²-80m²", "80m²-100m²", "100m²-130m²", "其他" };
            for (int i = 0; i < House.Length; i++)
            {
                HouseStructureRatios.Add(new StructureRatio { Title = House[i], Value = random.Next(20, 100) });
                AreaStructureRatios.Add(new StructureRatio { Title = Area[i], Value = random.Next(20, 100) });
            }

            StructureRatioSeries = HouseStructureRatios.AsLiveChartsPieSeries((value, series) =>
            {
                // here you can configure the series assigned to each value.
                series.Name = $"户型结构占比";
                //series.MaxOuterRadius = 0.8;
                series.DataLabelsSize = 12;
                series.DataLabelsPaint = new SolidColorPaint { Color = SKColors.White, SKTypeface = SKFontManager.Default.MatchCharacter('汉'), };
                series.DataLabelsPosition = LiveChartsCore.Measure.PolarLabelsPosition.Middle;
                series.DataLabelsFormatter = p => $"{p.Model.Title}";
                series.TooltipLabelFormatter = p => $"{p.Model.Title}：{p.PrimaryValue}%";
                series.Mapping = (sr, point) =>
                {
                    point.PrimaryValue = sr.Value;
                    point.SecondaryValue = point.Context.Index;
                };

            });

            AreaStructureRatioSeries = AreaStructureRatios.AsLiveChartsPieSeries((value, series) =>
            {
                // here you can configure the series assigned to each value.
                series.Name = $"面积结构占比";
                //series.Pushout = 5;
                series.InnerRadius = 40;
                series.DataLabelsSize = 12;
                series.DataLabelsPaint = new SolidColorPaint { Color = SKColors.White, SKTypeface = SKFontManager.Default.MatchCharacter('汉'), };
                series.DataLabelsPosition = LiveChartsCore.Measure.PolarLabelsPosition.Middle;
                series.DataLabelsFormatter = p => $"{p.Model.Title}";
                series.TooltipLabelFormatter = p => $"{p.Model.Title}：{p.PrimaryValue}%";
                series.Mapping = (sr, point) =>
                {
                    point.PrimaryValue = sr.Value;
                    point.SecondaryValue = point.Context.Index;
                };
            });
            #endregion


            #region 排行榜
            SaleBillboards = new() {
            new SaleBillboard{ Ranking=1,ProjectName="万科金域曦府",SaleCount=3621,SaleAmount=65421234},
            new SaleBillboard{ Ranking=2,ProjectName="星河智荟",SaleCount=3214,SaleAmount=564363535},
            new SaleBillboard{ Ranking=3,ProjectName="珠江天郦",SaleCount=3225,SaleAmount=45635},
            new SaleBillboard{ Ranking=4,ProjectName="龙湖天著",SaleCount=3142,SaleAmount=64646},
            new SaleBillboard{ Ranking=5,ProjectName="金地半山风华",SaleCount=2954,SaleAmount=34535},
            new SaleBillboard{ Ranking=6,ProjectName="富力南驰·富颐华庭",SaleCount=2865,SaleAmount=45646},
            new SaleBillboard{ Ranking=7,ProjectName="星河东悦湾",SaleCount=2841,SaleAmount=34534563},
            new SaleBillboard{ Ranking=8,ProjectName="合生湖山国际",SaleCount=2754,SaleAmount=34536345},
            new SaleBillboard{ Ranking=9,ProjectName="星瀚TOD",SaleCount=2541,SaleAmount=5464535},
            new SaleBillboard{ Ranking=10,ProjectName="珠江铂世湾",SaleCount=2425,SaleAmount=3453535},
            };
            #endregion

            #region 签约回款
            SignedSeries = new GaugeBuilder()
          .WithLabelsSize(30)
          .WithInnerRadius(60)
          .WithBackgroundInnerRadius(60)
          .WithBackground(new SolidColorPaint(new SKColor(100, 181, 246, 90)))
          .WithLabelsPosition(PolarLabelsPosition.ChartCenter)
          .AddValue(76, "签约完成率", SKColors.YellowGreen, SKColors.White) // defines the value and the color 
           .WithLabelFormatter(point => point.PrimaryValue + "%")
          .BuildSeries();

            PaymentCollectionSeries = new GaugeBuilder()
        .WithLabelsSize(30)
        .WithInnerRadius(60)
        .WithBackgroundInnerRadius(60)
        .WithBackground(new SolidColorPaint(new SKColor(100, 181, 246, 90)))
        .WithLabelsPosition(PolarLabelsPosition.ChartCenter)
        .AddValue(96, "回款完成率", SKColors.DeepSkyBlue, SKColors.White) // defines the value and the color 
        .WithLabelFormatter(point => point.PrimaryValue + "%")
        .BuildSeries();
            #endregion

            #region 购买力分析
            RadiusAxes = new PolarAxis[]
             {
                new PolarAxis
                {
                   TextSize = 12,
                    LabelsPaint = new SolidColorPaint(SKColors.White),
                    LabelsBackground = LvcColor.Empty,
                    SeparatorsPaint = new SolidColorPaint(SKColors.LightSlateGray) { StrokeThickness = 2 }
                }
             };

            //年龄结构
            List<StructureRatio> ages = new List<StructureRatio>() {
                new StructureRatio{ Title="18-25岁",Value=500},
                new StructureRatio{ Title="36-40岁",Value=5000},
                new StructureRatio{ Title="41-50岁",Value=7000},
                new StructureRatio{ Title="51-65岁",Value=800},
                new StructureRatio{ Title="其他",Value=1000},
            };

            AgeAngleAxes = new[]{
                new PolarAxis
                {
                    TextSize=14,
                    LabelsBackground = LvcColor.Empty,
                    LabelsRotation = LiveCharts.TangentAngle,
                    Labels = ages.Select(s=>s.Title).ToList(),
                    LabelsPaint = new SolidColorPaint
                    {
                        Color = SKColors.White,
                        SKTypeface = SKFontManager.Default.MatchCharacter('汉'), // 汉语 
                    },
                }
            };

            AgeSeries = new[]{
                new PolarLineSeries<StructureRatio>
                {
                    Values = ages,
                    LineSmoothness = 0,
                    GeometrySize= 0,
                    Fill = new SolidColorPaint(SKColors.Blue.WithAlpha(90)),
                    Name="购买力年龄结构",
                    Mapping = (sr, point) =>
                    {
                        point.PrimaryValue = sr.Value;
                    point.SecondaryValue = point.Context.Index;
                    },
                    TooltipLabelFormatter=point=>point.Model.Title+"："+ point.PrimaryValue+"万人"
                }
            };

            //收入结构
            List<StructureRatio> incomes = new List<StructureRatio>() {
                new StructureRatio{ Title="1-10万",Value=500},
                new StructureRatio{ Title="11-30万",Value=5000},
                new StructureRatio{ Title="31-100万",Value=7000},
                new StructureRatio{ Title="101-500万",Value=800},
                new StructureRatio{ Title="501-1000万",Value=1000},
                new StructureRatio{ Title="1000万以上",Value=1000},
            };
            IncomeAngleAxes = new[]{
                new PolarAxis
                {
                    TextSize=14,
                    LabelsBackground=LvcColor.Empty,

                    Labels = incomes.Select(s=>s.Title).ToList(),
                    LabelsPaint=new SolidColorPaint
                    {
                          Color = SKColors.White,
                       SKTypeface = SKFontManager.Default.MatchCharacter('汉'), // 汉语 
                    },
                }
            };

            IncomeSeries = new[]{
                new PolarLineSeries<StructureRatio>
                {
                   Values = incomes,
                            LineSmoothness = 0,
                           GeometrySize= 0,
                            Fill = new SolidColorPaint(SKColors.Gold.WithAlpha(50)),
                    Name="购买力年收入结构",
                    Mapping = (sr, point) =>
                    {
                        point.PrimaryValue = sr.Value;
                    point.SecondaryValue = point.Context.Index;
                    },
                    TooltipLabelFormatter=point=>point.Model.Title+"："+ point.PrimaryValue+"万人"
                }
            };
            #endregion

            #region 销售趋势
            var months = new[] { "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" };
            List<SaleTrend> saleTrends = new List<SaleTrend>();
            months.ToList().ForEach(item =>
            {
                saleTrends.Add(new SaleTrend() { Month = item, BackMoney = random.Next(10, 200), Signed = random.Next(10, 150), Subscribe = random.Next(10, 100) });
            });

            SaleTrendXAxes = new[]{
                new Axis
                {
                    // Use the labels property to define named labels.
                    Labels = months,
                    LabelsPaint=new SolidColorPaint
                    {
                        Color=SKColors.White,
                         SKTypeface = SKFontManager.Default.MatchCharacter('汉') // 汉语 
                    }
            }
            };

            SaleTrendSeries = new ISeries[]{
        new LineSeries<SaleTrend>
        {
            LineSmoothness = 1,
            Name = "回款",
            Values = saleTrends,
            Stroke = new SolidColorPaint(SKColors.DeepSkyBlue, 2),//曲线粗细和颜色
            GeometrySize = 7,//顶点大小
            GeometryStroke = new SolidColorPaint(SKColors.DeepSkyBlue, 2),//顶点粗细和颜色
            GeometryFill = new SolidColorPaint(SKColors.DarkBlue),//顶点填充颜色
            Fill = null,
            Mapping=(sr,point)=>{
            point.PrimaryValue=sr.BackMoney;
                point.SecondaryValue=point.Context.Index;
            },
              TooltipLabelFormatter=point=>$"{point.Model.Month}{point.Context.Series.Name}：{point.PrimaryValue}亿"
           // ScalesYAt = 0 // it will be scaled at the Axis[0] instance 
        },
        new LineSeries<SaleTrend>
        {
            Name = "认购",
            Values = saleTrends,
            Stroke = new SolidColorPaint(SKColors.Orange, 3),
            GeometrySize = 7,
            GeometryStroke = new SolidColorPaint(SKColors.Orange, 2),
            GeometryFill = new SolidColorPaint(SKColors.DarkOrange),//顶点填充颜色
            Fill = null,
              Mapping=(sr,point)=>{
            point.PrimaryValue=sr.Subscribe;
                point.SecondaryValue=point.Context.Index;
            },
                TooltipLabelFormatter=point=>$"{point.Model.Month}{point.Context.Series.Name}：{point.PrimaryValue}亿"
          //  ScalesYAt = 0 // it will be scaled at the Axis[0] instance 
        },
        new LineSeries<SaleTrend>
        {
            Name = "签约",
            Values = saleTrends,
            Stroke = new SolidColorPaint(SKColors.OrangeRed, 4),
            GeometrySize = 7,
            GeometryStroke = new SolidColorPaint(SKColors.OrangeRed, 2),
             GeometryFill = new SolidColorPaint(SKColors.DarkRed),
            Fill = null,
              Mapping=(sr,point)=>{
                point.PrimaryValue=sr.Signed;
                point.SecondaryValue=point.Context.Index;
                 // point.AsDataLabel=point.
            },
              TooltipLabelFormatter=point=>$"{point.Model.Month}{point.Context.Series.Name}：{point.PrimaryValue}亿"
            // ScalesYAt = 1 // it will be scaled at the YAxes[1] instance 
        },
        };
            #endregion

        }

        /// <summary>
        /// 模拟动态数据
        /// </summary>
        private void DynamicData()
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    await Task.Delay(5000);

                    try
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            TaskBars.Where(w => w.Title == "总营收").First().Value += random.Next(1, 20);
                            TaskBars.Where(w => w.Title == "已售总套数").First().Value += random.Next(1, 20);
                            TaskBars.Where(w => w.Title == "备案总套数").First().Value += random.Next(1, 20);

                            for (int i = 0; i < CityProfileSeries.Length; i++)
                            {
                                CityProfileSeries[i].Values.Cast<CityProfile>().ToList().ForEach(w =>
                                {
                                    w.Filing += random.Next(1, 20);
                                    w.Sold += random.Next(1, 20);
                                });
                            }

                            for (int i = 0; i < SaleBillboards.Count; i++)
                            {
                                SaleBillboards[i].SaleCount += random.Next(1, 50);
                                SaleBillboards[i].SaleAmount += random.Next(1, 50);
                            }

                            var SaleBillboardList = SaleBillboards.OrderByDescending(o => o.SaleAmount).ToList();
                            SaleBillboards.Clear();
                            for (int i = 0; i < SaleBillboardList.Count; i++)
                            {
                                SaleBillboardList[i].Ranking = i + 1;
                                SaleBillboards.Add(SaleBillboardList[i]);
                            }
                        });
                    }
                    catch (Exception ex)
                    {

                    }


                }

            });
        }

    }
}
